package com.nuoyuan.wx.aop;

import com.nuoyuan.wx.common.dto.BaseRespDto;
import com.nuoyuan.wx.common.utils.GsonUtil;
import com.nuoyuan.wx.common.utils.RedisUtil;
import com.nuoyuan.wx.service.respcode.UserRespCodeEnum;
import io.netty.util.internal.StringUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;
import java.util.Objects;

/**
 * @Package com.nuoyuan.wx
 * @ClassName LoginInterceptor
 * @Description TODO
 * @Author linus
 * @Date 2020-02-21 18:54
 * @Version 1.0
 **/

@Aspect
@Component
@Order(2)
public class AdminLoginAop {
    private static final Logger log = LogManager.getLogger(AdminLoginAop.class);
    @Autowired
    private RedisUtil redisUtil;

    @Around("execution(* com.nuoyuan.wx.admin.controller.*.*(..))")
    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {

        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        HttpServletResponse response = attributes.getResponse();

        // 除登录之外的其他接口都需要登录token验证
        log.info("请求URL : " + request.getRequestURL());
        log.info("请求IP : " + request.getRemoteAddr());

        NoLoginRequired noLoginAspect = ((MethodSignature)pjp.getSignature()).getMethod().getAnnotation(NoLoginRequired.class);
        if(Objects.isNull(noLoginAspect)) {
           if(StringUtil.isNullOrEmpty(request.getHeader("token"))) {
               response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
               return GsonUtil.toJson(BaseRespDto.buildErrorResp(UserRespCodeEnum.USER_NO_LOGIN.getCode(), UserRespCodeEnum.USER_NO_LOGIN.getMsg()));
           }
        }
        return pjp.proceed();
    }
}
